<template>
  <div class="user-header">
    <div class="buttonTop">
      <el-button type="primary" @click="handleAdd">+新增</el-button>
      <el-button type="danger" @click="handleDelList" style="padding: 5px"
        >批量删除</el-button
      >
    </div>
    <el-form :inline="true" :model="userFormInline" class="ef_1">
      <el-form-item>
        <el-input
          v-model="userFormInline.keywords"
          placeholder="请输入用户名检索"
          clearable
          prefix-icon="Search"
          class="ei_1"
          style="width: 190px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" v-has="hasValue.value"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>
  </div>
  <!-- 表格数据 -->
  <div class="table">
    <el-table
      :data="UsertableData"
      style="width: 100%; height: 494px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="30" />
      <el-table-column
        type="index"
        label="用户编号"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        v-for="item in UsertableLabel"
        align="center"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :width="item.width ? item.width : 125"
      />
      <el-table-column label="启用" prop="enable" width="70">
        <template #default="{ row }">
          <el-switch
            v-model="row.enable"
            inline-prompt
            inactive-color="#f56c6c"
            active-text="是"
            inactive-text="否"
            @change="changeUserStatus(row)"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="250">
        <!--Vue组件中定义一个插槽，row为当前行的数据，从父组件中拿到的，可以打印{{row}}查看 -->
        <!--如果#default="scope" scope为作用域对象，你可以拿到这个vue模版中的所有的对象和方法 -->
        <template #default="{ row }">
          <!-- {{ scope.row }} -->
          <el-button link type="primary" icon="Edit" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleUserRemove(row)"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            icon="Refresh"
            @click="resetPassword(row)"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      small
      background
      layout="prev, pager, next"
      :total="config.total"
      class="pager mt-5"
      @current-change="handleUserCurrentChange"
    />
  </div>
  <!--新增和编辑用户 dialogVisible：隐藏显示对话框视图 -->
  <el-dialog
    v-model="dialogVisible"
    :title="getAction.action === 'add' ? '新增用户' : '编辑用户'"
    :before-close="handleClose"
    class="dialog-form"
    draggable
    style="width: 40%"
  >
    <!-- form的prop和v-model双向绑定的要一致，否则会回显数据-->
    <el-form
      :model="formUserd"
      ref="userDialogForm"
      label-width="70px"
      label-position="right"
      :rules="rules"
    >
      <el-row>
        <el-col :lg="12">
          <el-form-item label="用户名:" prop="userName">
            <!-- spellcheck关闭语法检查 -->
            <el-input
              v-model="formUserd.userName"
              spellcheck="false"
              placeholder="请输入想要添加的用户名"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :lg="12">
          <el-form-item
            v-if="getAction.action === 'add'"
            label="密码:"
            prop="password"
          >
            <el-input
              v-model="formUserd.password"
              placeholder="请输入用户密码"
              clearable
              show-password
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :lg="24">
          <el-form-item label="角色:" prop="roleIds">
            <el-select
              v-model="formUserd.roleIds"
              style="width: 100%"
              multiple
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="2"
              placeholder="请选择"
            >
              <el-option
                v-for="item in roleList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :lg="12">
          <el-form-item label="手机号:" prop="phone">
            <!-- spellcheck关闭语法检查 -->
            <el-input
              v-model="formUserd.phone"
              spellcheck="false"
              placeholder="请输入手机号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :lg="12">
          <el-form-item label="邮箱:" prop="email">
            <!-- spellcheck关闭语法检查 -->
            <el-input
              v-model="formUserd.email"
              spellcheck="false"
              placeholder="请输入邮箱"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :lg="12">
          <el-form-item label="状态:" prop="enable">
            <el-select
              v-model="formUserd.enable"
              placeholder="请选择"
              clearable
            >
              <el-option label="正常" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :lg="12">
          <el-form-item label="性别:" prop="gender">
            <el-radio-group v-model="formUserd.gender">
              <el-radio label="1">男</el-radio>
              <el-radio label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="end">
        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import {
  computed,
  defineComponent,
  getCurrentInstance,
  onMounted,
  reactive,
  ref,
  toRaw,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import hasDirective from "../../../direactive/has";
export default defineComponent({
  directives: { has: hasDirective },
  setup() {
    // 设置按钮绑定的权限级别，目前不需要
    const hasValue = reactive({
      value: "quary",
    });
    const { proxy } = getCurrentInstance();
    const UsertableData = ref(null);
    const UsertableLabel = reactive([
      {
        prop: "userName",
        label: "用户名",
      },
      {
        prop: "phone",
        label: "手机号",
      },
      {
        prop: "gender",
        label: "性别",
      },
      {
        prop: "createBy",
        label: "创建人",
      },
      // {
      //   prop: "enable",
      //   label: "启用",
      // },
    ]);
    //改变用户状态（是否禁用）
    const changeUserStatus = (row) => {
      let status = row.enable === true ? "启用" : "禁用";
      ElMessageBox.confirm(
        `确定要 "${status}"  用户 "${row.userName}" 吗?`,
        "系统提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const id = row.id;
          const enable = row.enable === true ? 1 : 0;
          let res = await proxy.$api.user.changeStatusOrPassword({
            id,
            enable,
          });
          if (res) {
            ElMessage({
              type: "success",
              message: `用户 "${row.userName}" 状态已修改为 "${status}"`,
            });
            getUserData(config);
          }
        })
        .catch(() => {
          row.enable = row.enable === true ? false : true;
        });
    };
    //重置密码
    const resetPassword = (row) => {
      ElMessageBox.confirm("确定要重置该用户密码吗？默认：123456", "系统提示", {
        type: "warning",
        cancelButtonText: "取消",
        confirmButtonText: "确定",
      })
        .then(async () => {
          const password = await proxy.$md5("123456");
          const id = row.id;
          //enable在这里不等于1或者0，后端进行校验
          const enable = 101;
          let res = await proxy.$api.user.changeStatusOrPassword({
            id,
            enable,
            password,
          });
          if (res) {
            ElMessage({
              type: "success",
              message: `用户 "${row.userName}" 密码已重置"`,
            });
            getUserData(config);
          }
        })
        .catch(() => {});
    };
    //  查询用户、分页、搜索用户实体
    const config = reactive({
      total: 0,
      page: 1,
      size: 10,
      userName: "",
    });

    onMounted(() => {
      getUserData(config);
    });
    //  发送查询用户数据请求
    const getUserData = async (config) => {
      let res = await proxy.$api.user.getUserData(config);
      console.log(res);
      if (res) {
        const rulesMap = {
          1: "管理员",
          2: "普通用户",
        };
        config.total = res.data.total;
        if (res.data.dataList !== null && res.data.dataList.length !== 0) {
          UsertableData.value = res.data.dataList.map((item) => {
            item.gender = item.gender === 1 ? "男" : "女";
            item.enable = item.enable === 1 ? true : false;
            return item;
          });
        }
      }
    };
    // 页面跳转，触发分页条件查询
    const handleUserCurrentChange = (page) => {
      console.log(page);
      config.page = page;
      getUserData(config);
    };
    // 双向绑定，为了关键词搜索
    const userFormInline = reactive({
      keywords: "",
    });
    // 关键词搜索
    const handleSearch = () => {
      config.userName = userFormInline.keywords;
      getUserData(config);
    };
    // 控制弹框是否显示
    const dialogVisible = ref(false);
    // 弹框关闭按钮X掉触发
    const handleClose = (done) => {
      ElMessageBox.confirm("确定关闭吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          formUserd.password = "123456";
          proxy.$refs.userDialogForm.resetFields();
          done();
        })
        .catch(() => {
          // catch error
        });
    };
    // 添加用户的form数据接收绑定
    const formUserd = reactive({
      id: "",
      userName: "",
      phone: "",
      email: "",
      gender: "",
      enable: "",
      // 默认密码
      password: "123456",
      roleIds: "",
    });
    //  重置表单数据，防止数据回显
    const resetFormUserd = () => {
      Object.assign(formUserd, {
        id: "",
        userName: "",
        phone: "",
        email: "",
        gender: "",
        enable: "",
        // 默认密码
        password: "123456",
        roleIds: "",
      });
    };

    //表单校验
    const rules = reactive({
      userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
      enable: [{ required: true, message: "请选择状态", trigger: "blur" }],
    });

    // 新增用户，提交表单内容
    const onSubmit = () => {
      // 表单内容验证，表单的ref属性拿到表单，使用el-api校验
      proxy.$refs.userDialogForm.validate(async (valid) => {
        if (valid) {
          if (getAction.action === "add") {
            console.log("jinruadd");
            // 新增用户密码加密
            const userPassword = await proxy.$md5(formUserd.password);
            const currentUser = localStorage.getItem("username");
            let formUserdAdd = reactive({
              userName: formUserd.userName,
              password: userPassword,
              roleIds: formUserd.roleIds,
              phone: formUserd.phone,
              email: formUserd.email,
              gender: formUserd.gender,
              enable: formUserd.enable,
              createBy: currentUser,
            });
            // await只会返回给他最近的async回调函数！！！否则报错
            const res = await proxy.$api.user.addUser(formUserdAdd);
            // 如果成功，则清空form表单，并关闭弹框
            if (res) {
              // 拿到form表单的ref，使用form自带的清空表单api，ep提供
              //需要注意的是：使用validate、resetFields，需要在表单内容上加prop绑定表单相应属性才会生效
              proxy.$refs.userDialogForm.resetFields();
              // 关闭弹框
              dialogVisible.value = false;
              ElMessage({
                showClose: true,
                message: res.data,
                type: "success",
              });
              // 重新获取数据
              getUserData(config);
            }
            // 编辑用户信息
          } else if (getAction.action === "edit") {
            const formUserdEdit = reactive({
              id: formUserd.id,
              userName: formUserd.userName,
              password: formUserd.password,
              roleIds: formUserd.roleIds,
              phone: formUserd.phone,
              email: formUserd.email,
              gender: formUserd.gender,
              enable: formUserd.enable,
            });
            const res = await proxy.$api.user.updateUserData(formUserdEdit);
            if (res) {
              proxy.$refs.userDialogForm.resetFields();
              dialogVisible.value = false;
              ElMessage({
                showClose: true,
                message: res.data,
                type: "success",
              });
              // 重新获取数据
              getUserData(config);
            }
          }
        } else {
          ElMessage.error("请填写完整信息");
        }
      });
    };
    // 表单取消时也需要重置表单内容
    const handleCancel = () => {
      dialogVisible.value = false;
      formUserd.password = "123456";
      proxy.$refs.userDialogForm.resetFields();
    };
    // 复用模态框,新增和编辑
    const getAction = reactive({
      action: "add",
    });

    // 获取新增和编辑角色信息
    const roleList = ref();
    // 新增按钮
    const handleAdd = async () => {
      resetFormUserd();
      getAction.action = "add";
      let res = await proxy.$api.role.getRoleList();
      if (res) {
        console.log(
          "%c [ res ]-467",
          "font-size:13px; background:pink; color:#bf2c9f;",
          res
        );
        roleList.value = res.data;
        dialogVisible.value = true;
      }
    };
    // 编辑按钮
    const handleEdit = async (row) => {
      let userId = row.id;
      // 获取角色列表
      let res = await proxy.$api.role.getRoleList({ userId });
      if (res) {
        getAction.action = "edit";
        roleList.value = res.data.roles;
        dialogVisible.value = true;
        //事件循环机制，异步执行，避免在新增按钮触发是还可以看到编辑的值显示
        proxy.$nextTick(() => {
          // 浅拷贝
          Object.assign(formUserd, row);
          formUserd.enable = formUserd.enable == true ? "1" : "0";
          formUserd.gender = formUserd.gender == "男" ? "1" : "0";
          formUserd.roleIds = res.data.roleIds;
        });
      }
    };
    // 删除用户
    const handleUserRemove = (row) => {
      ElMessageBox.confirm("确定要删除吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await proxy.$api.user.deleteUser({ id: row.id });
          console.log(res);
          if (res) {
            ElMessage({
              showClose: true,
              message: res.data,
              type: "success",
            });
            getUserData(config);
          }
        })
        .catch(() => {
          // catch error
        });
    };
    let ids = reactive([]);
    // 批量选中
    const handleSelectionChange = (val) => {
      console.log(
        "%c [ val ]-447",
        "font-size:13px; background:pink; color:#bf2c9f;",
        val
      );
      ids = [];
      val.forEach((item) => {
        ids.push(item.id);
      });
    };
    // 批量删除
    const handleDelList = () => {
      ElMessageBox.confirm("确定要删除吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (ids.length !== 0) {
            console.log(
              "%c [ ids ]-466",
              "font-size:13px; background:pink; color:#bf2c9f;",
              ids
            );
            let res = await proxy.$api.user.batchDelUser(ids);
            if (res) {
              ElMessage({
                showClose: true,
                message: res.data,
                type: "success",
              });
              getUserData(config);
              ids = [];
            }
          } else {
            ElMessage({
              showClose: true,
              message: "请选择要删除的用户",
              type: "warning",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    return {
      UsertableData,
      UsertableLabel,
      config,
      handleUserCurrentChange,
      userFormInline,
      handleSearch,
      dialogVisible,
      handleClose,
      formUserd,
      rules,
      onSubmit,
      handleCancel,
      handleEdit,
      handleAdd,
      getAction,
      handleUserRemove,
      handleSelectionChange,
      handleDelList,
      hasValue,
      changeUserStatus,
      resetPassword,
      roleList,
    };
  },
});
</script>

<style lang="less" scoped>
.table {
  position: relative;
  height: 520px;
  .pager {
    position: absolute;
    right: 0;
    bottom: -10px;
  }
}
.user-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: -5px;
  padding-top: -10px;
}
.end {
  justify-content: end;
  margin-bottom: 0px;
}
// .el-dialog__header {
//   .el-dialog__headerbtn {
//     outline: none;
//   }
// }
</style>
